package zeebe.param;

import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.zeebe.client.ZeebeClient;
import io.zeebe.client.api.response.ActivatedJob;
import io.zeebe.client.api.worker.JobClient;
import io.zeebe.client.api.worker.JobHandler;

import java.util.HashMap;
import java.util.Map;

public class ParamJobWorkerHandler implements JobHandler {
    ZeebeClient zeebeClient;

    public ParamJobWorkerHandler(ZeebeClient client) {
        this.zeebeClient = client;
    }

    @Override
    public void handle(JobClient jobClient, ActivatedJob activatedJob) throws Exception {

        String param = activatedJob.getVariables();
        System.out.println("传入的参数为" + param);

        JsonObject data = new JsonObject(param);
        String obj = data.getString("hello");
        System.out.println("hello的值：" + obj);

        JsonObject jsonObject = new JsonObject(obj);
        Person person = jsonObject.mapTo(Person.class);
        System.out.println("反序列化JsonObject成功：" + Json.encode(person));

        jobClient.newCompleteCommand(activatedJob.getKey())
                .send()
                .join();

        Map messageMap = new HashMap();
        String correlationKey = "inputMsg";
        messageMap.put(correlationKey, correlationKey);
        zeebeClient.newSetVariablesCommand(activatedJob.getWorkflowInstanceKey())
                .variables(messageMap)
                .send()
                .join();

        zeebeClient.newPublishMessageCommand()
                .messageName(correlationKey)
                .correlationKey(correlationKey)
                .send()
                .join();
    }
}
